package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class register
 */
@WebServlet("/register")
public class register extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public register() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		
		String uuser = request.getParameter("username");
		String upass = request.getParameter("userpass");
		String utype = request.getParameter("usertype");
		String ufirstname = request.getParameter("userfname");
		String ulastname = request.getParameter("userlname");
		String uemail = request.getParameter("useremail");
	
	
		if(uuser==null|| upass==null|| utype==null|| ufirstname==null|| ulastname==null||uemail==null){
			out.println("Please fill out the form.");
		
		}
		else{
			addRecord(uuser, upass, utype, ufirstname, ulastname, uemail);
			request.setAttribute("vmsg", "You've registered a new user!");
			request.getRequestDispatcher("login.jsp").forward(request,response);
            return;
		}
		
	}
		
		public void addRecord(String username1, String userpassword1, String usertype1, String ufirstname1, String ulastname1, String uemail1){
			try {
				Class.forName("org.sqlite.JDBC");
				String url = "jdbc:sqlite:c:/Users/JayeM/workspace/MyWebProject/MyWebProject/WebContent/database/database.db";
				Connection con = DriverManager.getConnection(url);
					
				String sql = "insert into tbluserinfo values("+
				"?,?,?,?,?,?,?)";
					
				PreparedStatement pstmt = con.prepareStatement(sql);
				pstmt.setString(2, username1);
				pstmt.setString(3, userpassword1);
				pstmt.setString(4, usertype1);
				pstmt.setString(5, ufirstname1);
				pstmt.setString(6, ulastname1);
				pstmt.setString(7, uemail1);
				
				pstmt.executeUpdate();
				pstmt.close();
					
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
